package com.saa.common.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpUtils {

	/**
     * 以post或get方式调用对方接口方法，
     * @param pathUrl
     */
    public static String  httpDoPostOrGet(String pathUrl, String data){
    	String returnString = "";
        try {
            URL restServiceURL = new URL(pathUrl);
            HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Accept", "application/json");
            httpConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpConnection.setRequestProperty("contentType", "utf-8");
            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException(
                        "HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
            }
            BufferedReader responseBuffer = new BufferedReader(
                    new InputStreamReader((httpConnection.getInputStream()), StandardCharsets.UTF_8));
            String output = responseBuffer.readLine();
            // System.out.println("Output from Server: \n");
            StringBuffer buf = new StringBuffer();
            while (output != null) {
                buf.append(output).append("\r\n");
                output = responseBuffer.readLine();
            }
            responseBuffer.close();
            httpConnection.disconnect();
            returnString = buf.toString().trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnString;
    }
}
